﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Model;
using Dimebrain.TweetSharp.Extensions;
using System.Configuration;


namespace TwKarma.Web
{
	public class TweetSharpHelper
	{
        private static string _consumerKey;
        private static string _consumerSecret;

        private string ConsumerKey
        {
            get
            {
                if (_consumerKey == null)
                    _consumerKey = ConfigurationManager.AppSettings["TwitterAppKey"];
                return _consumerKey;
            }
        }
        private string ConsumerSecret
        {
            get
            {
                if (_consumerSecret == null)
                    _consumerSecret = ConfigurationManager.AppSettings["TwitterSecret"];
                return _consumerSecret;
            }
        }

		public OAuthToken Token
		{
			get { return HttpContext.Current.Session["OAuthToken"] as OAuthToken; }
			set { HttpContext.Current.Session["OAuthToken"] = value; }
		}

		public string UserAuthenticateUrl()
		{
			string authorizeUrl = string.Empty;
			Token = null;

			var result = FluentTwitter.CreateRequest()
				.Authentication
				.GetRequestToken(ConsumerKey, ConsumerSecret)
				.Request();

			if (!result.IsTwitterError)
				Token = result.AsToken();

			if (Token != null)
				authorizeUrl = FluentTwitter.CreateRequest()
					.Authentication
					.GetAuthorizationUrl(Token.Token);

			return authorizeUrl;
		}

		public void AuthenticateResponse(string requestToken)
		{
			var result = FluentTwitter.CreateRequest()
				.Authentication
				.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken)
				.Request().AsToken();

			if (result == null)
				throw new Exception("Failed to retrieve token for user.");

			FluentTwitter.CreateRequest()
				   .AuthenticateWith(ConsumerKey, ConsumerSecret, result.Token, result.TokenSecret)
				   .Account().VerifyCredentials().AsXml();

			Token = result;
		}

		private IFluentTwitter CreateRequest()
		{
            if (Token == null)
                return FluentTwitter.CreateRequest();

            return FluentTwitter.CreateRequest().AuthenticateWith(ConsumerKey, ConsumerSecret, Token.Token, Token.TokenSecret);
		}

		public string Request(Func<IFluentTwitter, ITwitterLeafNodeJson> twitterCall, bool useGZip)
		{
			IFluentTwitter ifluentTwitter = CreateRequest();
			if (ifluentTwitter == null)
				return "Could not create a request.";

			if (useGZip)
				ifluentTwitter = ifluentTwitter.Configuration.UseGzipCompression();

			var result = twitterCall(ifluentTwitter).AsJson().Request();

			if (result.IsTwitterError)
				return "Twitter Error";

			return result.Response;
		}
	}
}